<template>
  <div class="p-2">
    <!-- 聚合计算 - 聚合任务管理页面 -->
    <!-- 页面标题 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <div class="page-header">
        <div class="header-left">
          <el-button type="primary" plain icon="ArrowLeft" @click="goBack">返回列表</el-button>
          <el-divider direction="vertical" />
          <h3 class="page-title">{{ isEdit ? '编辑聚合指标' : '新建聚合指标' }}</h3>
        </div>
        <div class="header-right">
          <el-button type="info" plain icon="View" @click="previewConfig">预览配置</el-button>
          <el-button type="warning" plain icon="VideoPlay" @click="testIndicator">测试运行</el-button>
          <el-button type="success" icon="Check" @click="saveIndicator">保存指标</el-button>
        </div>
      </div>
    </el-card>

    <!-- 配置步骤 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="基础信息" description="配置指标基本信息" />
        <el-step title="数据源" description="选择数据源和字段" />
        <el-step title="聚合规则" description="设置聚合计算规则" />
        <el-step title="输出配置" description="配置输出和存储" />
        <el-step title="完成" description="保存并启用指标" />
      </el-steps>
    </el-card>

    <!-- 配置表单 -->
    <el-card shadow="hover">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <!-- 步骤1：基础信息 -->
        <div v-show="currentStep === 0">
          <h4 class="step-title">基础信息配置</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="指标名称" prop="indicatorName">
                <el-input v-model="form.indicatorName" placeholder="请输入指标名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="指标编码" prop="indicatorCode">
                <el-input v-model="form.indicatorCode" placeholder="请输入指标编码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="指标分类" prop="category">
                <el-select v-model="form.category" placeholder="请选择指标分类" style="width: 100%">
                  <el-option label="设备监控" value="device_monitor" />
                  <el-option label="系统性能" value="system_performance" />
                  <el-option label="业务统计" value="business_stats" />
                  <el-option label="告警分析" value="alarm_analysis" />
                  <el-option label="数据质量" value="data_quality" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                  <el-option label="高" value="high" />
                  <el-option label="中" value="medium" />
                  <el-option label="低" value="low" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="指标描述" prop="description">
            <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入指标描述" />
          </el-form-item>
          <el-form-item label="标签" prop="tags">
            <el-tag
              v-for="tag in form.tags"
              :key="tag"
              closable
              @close="removeTag(tag)"
              style="margin-right: 8px; margin-bottom: 8px"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="tagInputVisible"
              ref="tagInputRef"
              v-model="tagInputValue"
              size="small"
              style="width: 120px"
              @keyup.enter="addTag"
              @blur="addTag"
            />
            <el-button v-else size="small" @click="showTagInput">+ 添加标签</el-button>
          </el-form-item>
        </div>

        <!-- 步骤2：数据源配置 -->
        <div v-show="currentStep === 1">
          <h4 class="step-title">数据源配置</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源类型" prop="dataSourceType">
                <el-select v-model="form.dataSourceType" placeholder="请选择数据源类型" style="width: 100%" @change="onDataSourceTypeChange">
                  <el-option label="数据库表" value="database" />
                  <el-option label="消息队列" value="message_queue" />
                  <el-option label="API接口" value="api" />
                  <el-option label="文件数据" value="file" />
                  <el-option label="实时流" value="stream" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="dataSourceName">
                <el-select v-model="form.dataSourceName" placeholder="请选择数据源" style="width: 100%" @change="onDataSourceChange">
                  <el-option v-for="source in dataSourceList" :key="source.value" :label="source.label" :value="source.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="数据表/主题" prop="dataTable">
            <el-select v-model="form.dataTable" placeholder="请选择数据表或主题" style="width: 300px" @change="onDataTableChange">
              <el-option v-for="table in dataTableList" :key="table.value" :label="table.label" :value="table.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="字段选择" prop="selectedFields">
            <el-transfer
              v-model="form.selectedFields"
              :data="availableFields"
              :titles="['可用字段', '已选字段']"
              :button-texts="['移除', '选择']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              filterable
              filter-placeholder="搜索字段"
              style="text-align: left; display: inline-block"
            />
          </el-form-item>
          <el-form-item label="过滤条件" prop="filterCondition">
            <div class="filter-builder">
              <el-button type="primary" plain icon="Plus" @click="addFilterCondition">添加条件</el-button>
              <div v-for="(condition, index) in form.filterConditions" :key="index" class="filter-item">
                <el-row :gutter="10" style="margin-top: 10px">
                  <el-col :span="5">
                    <el-select v-model="condition.field" placeholder="字段">
                      <el-option v-for="field in selectedFieldOptions" :key="field.value" :label="field.label" :value="field.value" />
                    </el-select>
                  </el-col>
                  <el-col :span="4">
                    <el-select v-model="condition.operator" placeholder="操作符">
                      <el-option label="等于" value="=" />
                      <el-option label="不等于" value="!=" />
                      <el-option label="大于" value=">" />
                      <el-option label="小于" value="<" />
                      <el-option label="包含" value="LIKE" />
                      <el-option label="在范围内" value="IN" />
                    </el-select>
                  </el-col>
                  <el-col :span="6">
                    <el-input v-model="condition.value" placeholder="值" />
                  </el-col>
                  <el-col :span="3">
                    <el-select v-model="condition.logic" placeholder="逻辑" v-if="index < form.filterConditions.length - 1">
                      <el-option label="AND" value="AND" />
                      <el-option label="OR" value="OR" />
                    </el-select>
                  </el-col>
                  <el-col :span="2">
                    <el-button type="danger" plain icon="Delete" @click="removeFilterCondition(index)"></el-button>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-form-item>
        </div>

        <!-- 步骤3：聚合规则配置 -->
        <div v-show="currentStep === 2">
          <h4 class="step-title">聚合规则配置</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="聚合类型" prop="aggregationType">
                <el-select v-model="form.aggregationType" placeholder="请选择聚合类型" style="width: 100%">
                  <el-option label="求和 (SUM)" value="sum" />
                  <el-option label="平均值 (AVG)" value="avg" />
                  <el-option label="最大值 (MAX)" value="max" />
                  <el-option label="最小值 (MIN)" value="min" />
                  <el-option label="计数 (COUNT)" value="count" />
                  <el-option label="去重计数 (DISTINCT COUNT)" value="count_distinct" />
                  <el-option label="标准差 (STDDEV)" value="stddev" />
                  <el-option label="方差 (VARIANCE)" value="variance" />
                  <el-option label="中位数 (MEDIAN)" value="median" />
                  <el-option label="百分位数 (PERCENTILE)" value="percentile" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="聚合字段" prop="aggregateField">
                <el-select v-model="form.aggregateField" placeholder="请选择聚合字段" style="width: 100%">
                  <el-option v-for="field in selectedFieldOptions" :key="field.value" :label="field.label" :value="field.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="时间窗口" prop="timeWindow">
                <el-input-number v-model="form.timeWindow" :min="1" placeholder="时间窗口" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="时间单位" prop="timeUnit">
                <el-select v-model="form.timeUnit" style="width: 100%">
                  <el-option label="秒" value="second" />
                  <el-option label="分钟" value="minute" />
                  <el-option label="小时" value="hour" />
                  <el-option label="天" value="day" />
                  <el-option label="周" value="week" />
                  <el-option label="月" value="month" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计算频率" prop="frequency">
                <el-input-number v-model="form.frequency" :min="1" placeholder="计算频率" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="频率单位" prop="frequencyUnit">
                <el-select v-model="form.frequencyUnit" style="width: 100%">
                  <el-option label="秒" value="second" />
                  <el-option label="分钟" value="minute" />
                  <el-option label="小时" value="hour" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="分组字段" prop="groupByFields">
            <el-select v-model="form.groupByFields" multiple placeholder="请选择分组字段" style="width: 100%">
              <el-option v-for="field in selectedFieldOptions" :key="field.value" :label="field.label" :value="field.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="自定义公式" prop="customFormula">
            <el-input v-model="form.customFormula" type="textarea" :rows="4" placeholder="请输入自定义计算公式（可选）" />
            <div class="formula-help">
              <el-text type="info" size="small">
                支持的函数：SUM(), AVG(), MAX(), MIN(), COUNT(), STDDEV()等<br/>
                示例：SUM(field1) / COUNT(field2) * 100
              </el-text>
            </div>
          </el-form-item>
        </div>

        <!-- 步骤4：输出配置 -->
        <div v-show="currentStep === 3">
          <h4 class="step-title">输出配置</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="输出格式" prop="outputFormat">
                <el-select v-model="form.outputFormat" placeholder="请选择输出格式" style="width: 100%">
                  <el-option label="JSON" value="json" />
                  <el-option label="CSV" value="csv" />
                  <el-option label="XML" value="xml" />
                  <el-option label="自定义" value="custom" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数值精度" prop="precision">
                <el-input-number v-model="form.precision" :min="0" :max="10" placeholder="小数位数" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="存储配置">
            <el-checkbox-group v-model="form.storageOptions">
              <el-checkbox label="database">存储到数据库</el-checkbox>
              <el-checkbox label="file">保存到文件</el-checkbox>
              <el-checkbox label="cache">缓存结果</el-checkbox>
              <el-checkbox label="message_queue">发送到消息队列</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="告警配置" prop="alertConfig">
            <el-switch v-model="form.alertEnabled" active-text="启用告警" inactive-text="禁用告警" />
            <div v-if="form.alertEnabled" style="margin-top: 15px">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="告警条件">
                    <el-select v-model="form.alertCondition" placeholder="选择条件">
                      <el-option label="大于" value=">" />
                      <el-option label="小于" value="<" />
                      <el-option label="等于" value="=" />
                      <el-option label="不等于" value="!=" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="阈值">
                    <el-input-number v-model="form.alertThreshold" placeholder="阈值" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="告警级别">
                    <el-select v-model="form.alertLevel" placeholder="选择级别">
                      <el-option label="低" value="low" />
                      <el-option label="中" value="medium" />
                      <el-option label="高" value="high" />
                      <el-option label="紧急" value="critical" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
          <el-form-item label="输出字段映射">
            <el-table :data="form.outputMapping" border style="width: 100%">
              <el-table-column label="源字段" prop="sourceField" width="200">
                <template #default="scope">
                  <el-select v-model="scope.row.sourceField" placeholder="选择字段">
                    <el-option v-for="field in selectedFieldOptions" :key="field.value" :label="field.label" :value="field.value" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="输出字段名" prop="outputField" width="200">
                <template #default="scope">
                  <el-input v-model="scope.row.outputField" placeholder="输出字段名" />
                </template>
              </el-table-column>
              <el-table-column label="数据类型" prop="dataType" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.dataType" placeholder="数据类型">
                    <el-option label="字符串" value="string" />
                    <el-option label="整数" value="integer" />
                    <el-option label="浮点数" value="float" />
                    <el-option label="布尔值" value="boolean" />
                    <el-option label="日期" value="date" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="描述" prop="description">
                <template #default="scope">
                  <el-input v-model="scope.row.description" placeholder="字段描述" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140">
                <template #default="scope">
                  <el-button type="danger" plain icon="Delete" @click="removeOutputMapping(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" plain icon="Plus" @click="addOutputMapping" style="margin-top: 10px">添加字段映射</el-button>
          </el-form-item>
        </div>

        <!-- 步骤5：完成配置 -->
        <div v-show="currentStep === 4">
          <h4 class="step-title">配置完成</h4>
          <el-result icon="success" title="指标配置完成" sub-title="请确认配置信息并保存指标">
            <template #extra>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="指标名称">{{ form.indicatorName }}</el-descriptions-item>
                <el-descriptions-item label="指标编码">{{ form.indicatorCode }}</el-descriptions-item>
                <el-descriptions-item label="数据源">{{ form.dataSourceName }}</el-descriptions-item>
                <el-descriptions-item label="聚合类型">{{ getAggregationTypeText(form.aggregationType) }}</el-descriptions-item>
                <el-descriptions-item label="时间窗口">{{ form.timeWindow }}{{ getTimeUnitText(form.timeUnit) }}</el-descriptions-item>
                <el-descriptions-item label="计算频率">{{ form.frequency }}{{ getTimeUnitText(form.frequencyUnit) }}</el-descriptions-item>
              </el-descriptions>
            </template>
          </el-result>
          <el-form-item label="启动配置">
            <el-switch v-model="form.autoStart" active-text="保存后自动启动" inactive-text="保存后手动启动" />
          </el-form-item>
        </div>
      </el-form>

      <!-- 步骤操作按钮 -->
      <div class="step-actions">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button v-if="currentStep < 4" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="currentStep === 4" type="success" @click="saveIndicator">保存指标</el-button>
      </div>
    </el-card>

    <!-- 配置预览对话框 -->
    <el-dialog title="配置预览" v-model="previewDialog.visible" width="800px" append-to-body>
      <el-tabs v-model="previewTab">
        <el-tab-pane label="JSON配置" name="json">
          <pre class="config-preview">{{ JSON.stringify(form, null, 2) }}</pre>
        </el-tab-pane>
        <el-tab-pane label="SQL预览" name="sql">
          <pre class="config-preview">{{ generateSQL() }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 测试运行对话框 -->
    <el-dialog title="测试运行" v-model="testDialog.visible" width="600px" append-to-body>
      <div class="test-container">
        <el-alert title="测试说明" type="info" show-icon :closable="false" style="margin-bottom: 20px">
          <p>将使用当前配置对最近的数据进行测试计算，验证指标配置的正确性。</p>
        </el-alert>
        <el-form label-width="120px">
          <el-form-item label="测试数据量">
            <el-input-number v-model="testConfig.dataLimit" :min="10" :max="10000" />
          </el-form-item>
          <el-form-item label="测试时间范围">
            <el-date-picker
              v-model="testConfig.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <div v-if="testResult.visible" class="test-result">
          <el-divider>测试结果</el-divider>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="执行状态">
              <el-tag :type="testResult.success ? 'success' : 'danger'">
                {{ testResult.success ? '成功' : '失败' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="执行时间">{{ testResult.duration }}ms</el-descriptions-item>
            <el-descriptions-item label="处理数据量">{{ testResult.processedCount }}条</el-descriptions-item>
            <el-descriptions-item label="计算结果">{{ testResult.result }}</el-descriptions-item>
          </el-descriptions>
          <div v-if="!testResult.success" class="error-info">
            <el-alert title="错误信息" type="error" :description="testResult.error" show-icon />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="testDialog.visible = false">关闭</el-button>
          <el-button type="primary" @click="runTest" :loading="testRunning">开始测试</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="IndicatorTask" lang="ts">
import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Plus, Delete, Check, View, VideoPlay } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const currentStep = ref(0)
const isEdit = ref(false)
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const previewTab = ref('json')
const testRunning = ref(false)

// 对话框状态
const previewDialog = reactive({
  visible: false
})

const testDialog = reactive({
  visible: false
})

// 测试配置
const testConfig = reactive({
  dataLimit: 1000,
  timeRange: []
})

// 测试结果
const testResult = reactive({
  visible: false,
  success: false,
  duration: 0,
  processedCount: 0,
  result: '',
  error: ''
})

// 表单数据
const form = reactive({
  indicatorName: '',
  indicatorCode: '',
  category: '',
  priority: 'medium',
  description: '',
  tags: [],
  dataSourceType: '',
  dataSourceName: '',
  dataTable: '',
  selectedFields: [],
  filterConditions: [],
  aggregationType: '',
  aggregateField: '',
  timeWindow: 1,
  timeUnit: 'hour',
  frequency: 1,
  frequencyUnit: 'minute',
  groupByFields: [],
  customFormula: '',
  outputFormat: 'json',
  precision: 2,
  storageOptions: ['database'],
  alertEnabled: false,
  alertCondition: '>',
  alertThreshold: 0,
  alertLevel: 'medium',
  outputMapping: [],
  autoStart: true
})

// 表单验证规则
const rules = {
  indicatorName: [{ required: true, message: '请输入指标名称', trigger: 'blur' }],
  indicatorCode: [{ required: true, message: '请输入指标编码', trigger: 'blur' }],
  category: [{ required: true, message: '请选择指标分类', trigger: 'change' }],
  dataSourceType: [{ required: true, message: '请选择数据源类型', trigger: 'change' }],
  dataSourceName: [{ required: true, message: '请选择数据源', trigger: 'change' }],
  aggregationType: [{ required: true, message: '请选择聚合类型', trigger: 'change' }],
  aggregateField: [{ required: true, message: '请选择聚合字段', trigger: 'change' }]
}

// 数据源列表
const dataSourceList = ref([
  { label: 'MySQL主库', value: 'mysql_main' },
  { label: 'PostgreSQL', value: 'postgresql' },
  { label: 'InfluxDB', value: 'influxdb' },
  { label: 'Kafka集群', value: 'kafka_cluster' },
  { label: 'Redis缓存', value: 'redis_cache' }
])

// 数据表列表
const dataTableList = ref([])

// 可用字段列表
const availableFields = ref([])

// 已选字段选项
const selectedFieldOptions = computed(() => {
  return availableFields.value.filter(field => form.selectedFields.includes(field.key))
})

// 数据源类型变化
const onDataSourceTypeChange = () => {
  form.dataSourceName = ''
  form.dataTable = ''
  form.selectedFields = []
  dataTableList.value = []
  availableFields.value = []
}

// 数据源变化
const onDataSourceChange = () => {
  form.dataTable = ''
  form.selectedFields = []
  availableFields.value = []
  
  // 模拟获取数据表列表
  setTimeout(() => {
    dataTableList.value = [
      { label: 'device_data', value: 'device_data' },
      { label: 'sensor_readings', value: 'sensor_readings' },
      { label: 'system_logs', value: 'system_logs' },
      { label: 'alarm_events', value: 'alarm_events' },
      { label: 'user_activities', value: 'user_activities' }
    ]
  }, 500)
}

// 数据表变化
const onDataTableChange = () => {
  form.selectedFields = []
  
  // 模拟获取字段列表
  setTimeout(() => {
    availableFields.value = [
      { key: 'id', label: 'ID', value: 'id' },
      { key: 'device_id', label: '设备ID', value: 'device_id' },
      { key: 'temperature', label: '温度', value: 'temperature' },
      { key: 'humidity', label: '湿度', value: 'humidity' },
      { key: 'pressure', label: '压力', value: 'pressure' },
      { key: 'timestamp', label: '时间戳', value: 'timestamp' },
      { key: 'status', label: '状态', value: 'status' },
      { key: 'location', label: '位置', value: 'location' }
    ]
  }, 500)
}

// 添加标签
const addTag = () => {
  if (tagInputValue.value && !form.tags.includes(tagInputValue.value)) {
    form.tags.push(tagInputValue.value)
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 移除标签
const removeTag = (tag: string) => {
  const index = form.tags.indexOf(tag)
  if (index > -1) {
    form.tags.splice(index, 1)
  }
}

// 显示标签输入
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    // 聚焦到输入框
  })
}

// 添加过滤条件
const addFilterCondition = () => {
  form.filterConditions.push({
    field: '',
    operator: '=',
    value: '',
    logic: 'AND'
  })
}

// 移除过滤条件
const removeFilterCondition = (index: number) => {
  form.filterConditions.splice(index, 1)
}

// 添加输出映射
const addOutputMapping = () => {
  form.outputMapping.push({
    sourceField: '',
    outputField: '',
    dataType: 'string',
    description: ''
  })
}

// 移除输出映射
const removeOutputMapping = (index: number) => {
  form.outputMapping.splice(index, 1)
}

// 获取聚合类型文本
const getAggregationTypeText = (type: string) => {
  const typeMap = {
    sum: '求和',
    avg: '平均值',
    max: '最大值',
    min: '最小值',
    count: '计数',
    count_distinct: '去重计数',
    stddev: '标准差',
    variance: '方差',
    median: '中位数',
    percentile: '百分位数'
  }
  return typeMap[type] || type
}

// 获取时间单位文本
const getTimeUnitText = (unit: string) => {
  const unitMap = {
    second: '秒',
    minute: '分钟',
    hour: '小时',
    day: '天',
    week: '周',
    month: '月'
  }
  return unitMap[unit] || unit
}

// 生成SQL预览
const generateSQL = () => {
  if (!form.aggregationType || !form.aggregateField || !form.dataTable) {
    return '-- 请完成基础配置后查看SQL预览'
  }
  
  let sql = `SELECT `
  
  // 分组字段
  if (form.groupByFields.length > 0) {
    sql += form.groupByFields.join(', ') + ', '
  }
  
  // 聚合函数
  sql += `${form.aggregationType.toUpperCase()}(${form.aggregateField}) as result\n`
  sql += `FROM ${form.dataTable}\n`
  
  // 过滤条件
  if (form.filterConditions.length > 0) {
    sql += 'WHERE '
    form.filterConditions.forEach((condition, index) => {
      sql += `${condition.field} ${condition.operator} '${condition.value}'`
      if (index < form.filterConditions.length - 1) {
        sql += ` ${condition.logic} `
      }
    })
    sql += '\n'
  }
  
  // 分组
  if (form.groupByFields.length > 0) {
    sql += `GROUP BY ${form.groupByFields.join(', ')}\n`
  }
  
  return sql
}

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 下一步
const nextStep = () => {
  if (currentStep.value < 4) {
    currentStep.value++
  }
}

// 返回列表
const goBack = () => {
  router.push('/iot/aggregateCompute/indicatorList')
}

// 预览配置
const previewConfig = () => {
  previewDialog.visible = true
}

// 测试指标
const testIndicator = () => {
  testDialog.visible = true
  testResult.visible = false
}

// 运行测试
const runTest = () => {
  testRunning.value = true
  
  // 模拟测试运行
  setTimeout(() => {
    testResult.visible = true
    testResult.success = Math.random() > 0.3 // 70%成功率
    testResult.duration = Math.floor(Math.random() * 2000) + 500
    testResult.processedCount = Math.floor(Math.random() * 1000) + 100
    
    if (testResult.success) {
      testResult.result = '25.6'
      testResult.error = ''
    } else {
      testResult.result = ''
      testResult.error = '数据源连接失败或字段不存在'
    }
    
    testRunning.value = false
  }, 2000)
}

// 保存指标
const saveIndicator = () => {
  ElMessageBox.confirm('确认保存指标配置？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('指标保存成功')
    router.push('/iot/aggregateCompute/indicatorList')
  })
}

// 组件挂载
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.header-left {
  display: flex;
  align-items: center;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.header-right {
  display: flex;
  gap: 10px;
}

.step-title {
  color: #303133;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.step-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.step-actions .el-button {
  margin: 0 10px;
}

.filter-builder {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background: #fafafa;
}

.filter-item {
  margin-bottom: 10px;
}

.formula-help {
  margin-top: 8px;
  padding: 8px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
}

.config-preview {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #303133;
  margin: 0;
}

.test-container {
  min-height: 200px;
}

.test-result {
  margin-top: 20px;
}

.error-info {
  margin-top: 15px;
}
</style>